let express = require("express");
let expressWebSocket = require("express-ws");
let exec = require("child_process").exec;
let app = express();
function localServer() {
  app.use(express.static(__dirname));
  expressWebSocket(app, null, {
    perMessageDeflate: true,
  });
  // app.ws("/rtsp/", rtspRequestHandle);
  app.listen(8888);
  console.log("express listened");
}
localServer();

/*为app添加中间件处理跨域请求*/
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  next();
});
// get方式监听/login请求
app.get("/rtspTransport", (req, res) => {
  console.log("请求", req.query);
  // 参数可根据自己需求调整
  let url = req.query.url;
  let dirUrl = req.query.dirUrl;
  let cmdOrder = `ffmpeg -rtsp_transport tcp -i "${url}" -r 30 -q 0 -f mpegts -codec:v mpeg1video -s 800x600 http://127.0.0.1:8084/123456/${dirUrl}`;
  let result = exec(
    cmdOrder,
    {
      maxBuffer: 1024 * 2000,
    },
    // function (err, stdout, stderr) {
    //   if (err) {
    //     console.log("error", err);
    //   } else if (stderr.lenght > 0) {
    //     console.log("stderr", stderr);
    //   } else {
    //   }
    // }
  );
  // 推流成功，返回推流端口号
  res.send({ code: 0, mag: "成功", pId: result.pid });
});
// 用之前推流成功的端口号关闭之前的推流
app.get("/stopTransport", (req, res) => {
  let pId = req.query.pId;
  let cmdOrder = `kill -s 9 ${pId}`;
  let result = exec(
    cmdOrder,
    {
      maxBuffer: 1024 * 2000,
    },
    function (err, stdout, stderr) {
      if (err) {
        console.log("error", err);
      } else if (stderr.lenght > 0) {
        console.log("stderr", stderr);
      } else {
      }
    }
  );
  res.send({ code: 0, mag: "成功" });
});
